package com.atguigu.lease.web.admin.controller.system;


import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserItemVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


@Tag(name = "后台用户信息管理")
@RestController
@RequestMapping("/admin/system/user")
public class SystemUserController {

    @Autowired
    private SystemUserService systemUserService;

    @Operation(summary = "根据条件分页查询后台用户列表")
    @GetMapping("page")
    public Result<IPage<SystemUserItemVo>> page(@RequestParam long current, @RequestParam long size, SystemUserQueryVo queryVo) {
        Page<SystemUserItemVo> page = new Page<>(current, size);
        //SQL不能返回密码
        systemUserService.customPage(page, queryVo);
        return Result.ok(page);
    }

    @Operation(summary = "根据ID查询后台用户信息")
    @GetMapping("getById")
    public Result<SystemUserItemVo> getById(@RequestParam Long id) {
        //SQL不能返回密码
        SystemUserItemVo systemUserItemVo = systemUserService.customGetById(id);
        return Result.ok(systemUserItemVo);
    }

    @Operation(summary = "保存或更新后台用户信息")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody SystemUser systemUser) {

        Long userId = systemUser.getId();
        //修改
        if (userId != null) {
            //可能修改密码也可能不修改密码
            //修改了密码,判断密码是否正确
            String formPassword = systemUser.getPassword();
            if (!ObjectUtils.isEmpty(formPassword)) {
                String dbPassword = systemUserService.getById(userId).getPassword();
                //md5依赖: commons-codec,在web包导入
                if (!dbPassword.equals(DigestUtils.md5Hex(formPassword))) {
                    throw new LeaseException(ResultCodeEnum.PARAM_ERROR);
                }
                //修改,如果改了密码,要加密再放到数据库
                systemUser.setPassword(DigestUtils.md5Hex(formPassword));
            }
/*
            //前端传递password字段,如果没有填写,会传递空字符串,MP默认会认为空字符串是有效字符,将其修改
            //解决方案: 如果是空字符串设为null,或者将MP的修改策略从默认的not-null改为not-empty
            else if (Objects.equals(formPassword, "")){
                systemUser.setPassword(null);
            }
*/
        }

        //保存,存密码之前先加密
        if (userId == null) {
            systemUser.setPassword(DigestUtils.md5Hex(systemUser.getPassword()));
        }

        systemUserService.saveOrUpdate(systemUser);
        return Result.ok();
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md5Hex(""));
        System.out.println(DigestUtils.md5Hex("123456"));
    }
    @Operation(summary = "判断后台用户名是否可用")
    @GetMapping("isUserNameAvailable")
    public Result<Boolean> isUsernameExists(@RequestParam String username, @RequestParam(required = false) Long userId) {
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername, username);
        systemUserLambdaQueryWrapper.eq(!ObjectUtils.isEmpty(userId), SystemUser::getId, userId);
        long count = systemUserService.count(systemUserLambdaQueryWrapper);
        if (count > 0) throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_EXIST_ERROR);

        return Result.ok();
    }

    @DeleteMapping("deleteById")
    @Operation(summary = "根据ID删除后台用户信息")
    public Result removeById(@RequestParam Long id) {
        systemUserService.removeById(id);
        return Result.ok();
    }

    @Operation(summary = "根据ID修改后台用户状态")
    @PostMapping("updateStatusByUserId")
    public Result updateStatusByUserId(@RequestParam Long id, @RequestParam BaseStatus status) {
        LambdaUpdateWrapper<SystemUser> systemUserLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        systemUserLambdaUpdateWrapper.eq(SystemUser::getId, id);
        systemUserLambdaUpdateWrapper.set(SystemUser::getStatus, status);
        systemUserService.update(systemUserLambdaUpdateWrapper);
        return Result.ok();
    }
}
